<?php

namespace globalunit\utils;

use MultipleIterator;
use QYS\Log\Log;
use \Swoole\Coroutine\Http\Client;
class CoroutineCurl{

    public static function request($host, $url, $cookie = null){
        $cli = new Client($host, 443, true);
        $cli->set(['timeout' => 10.0,'keep_alive' => true,]);
        $cli->setHeaders([
            'Host' => $host,
            "User-Agent" => 'Chrome/49.0.2587.3',
            'Accept' => 'text/html,application/xhtml+xml,application/xml,application/json',
            'Accept-Encoding' => 'gzip',
            'Content-Type'=> 'application/json',
            'cookie' => $cookie
        ]);
        $cli->setMethod("GET");
        $cli->execute($url);
        $statusCode = $cli->statusCode;
        Log::var_dump(["statusCode" => $statusCode]);
        if($statusCode != 200){
            return null;
        }
        $result = $cli->body;
        $result = json_decode($result, true);
        $cli->close();
        return $result;
    }

    public static function post($host, $url, $body = null, $cookie = null){
        $cli = new Client($host, 443, true);
        $cli->set(['timeout' => 10.0,'keep_alive' => true,]);
        $cli->setHeaders([
            'Host' => $host,
            "User-Agent" => 'Chrome/49.0.2587.3',
            'Accept' => 'text/html,application/xhtml+xml,application/xml,application/json',
            'Accept-Encoding' => 'gzip',
            'Content-Type'=> 'application/json',
            'cookie' => $cookie
        ]);
        $cli->setMethod("POST");
        if(!empty($body)){
            $cli->setData($body);
        }
        $cli->execute($url);
        $statusCode = $cli->statusCode;
        Log::var_dump(["statusCode" => $statusCode]);
        if($statusCode != 200){
            return null;
        }
        $result = $cli->body;
        $result = json_decode($result, true);
        $cli->close();
        return $result;
    }
}


